package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    @Override
    public List<User> findAll() {

        List<User> users = new ArrayList<>();
        String url = "jdbc:mysql://localhost:3306/jdbc";
        String user = "root";
        String password = "080472";
        //jdbc查询数据库操作
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;

        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2.获取连接
            conn = DriverManager.getConnection(url, user, password);

            //3.编写SQL语句
            String sql = "select * from sys_user";

            //4.预处理SQL语句
            preparedStatement = conn.prepareStatement(sql);

            //5.如有参数，设置参数

            //6.执行SQL语句
            rs = preparedStatement.executeQuery();

            //7.如果是查询就遍历结果/
            while (rs.next()) {
                User u = new User();
                u.setId(rs.getInt(1));
                u.setName(rs.getString(2));
                u.setPass(rs.getString(3));
                users.add(u);
            }
            return users;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //8.关闭资源
            try {
                //NullPointException
                if (rs != null) {
                    rs.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
